package com.cn.pattern

import scala.collection.mutable.ListBuffer

trait TaskListener {
  def before(): Unit

  def after(): Unit
}


object DorisListener {
  val taskFlag = "DorisListener"

  def apply(): DorisListener = new DorisListener()
}

class DorisListener extends TaskListener {
  override def before(): Unit = println("DorisListener before")

  override def after(): Unit = println("DorisListener after")
}

object HiveListener {
  val taskFlag = "HiveListener"

  def apply(): HiveListener = new HiveListener()
}

class HiveListener extends TaskListener {
  override def before(): Unit = {
    for (i <- 1 to 6) {
      Thread.sleep(1000)
      println(s"HiveListener before ${i.toString}")
    }
  }

  override def after(): Unit = println("HiveListener after")
}


object CKListener {
  val taskFlag = "CKListener"

  def apply(): CKListener = new CKListener()
}

class CKListener extends TaskListener {
  override def before(): Unit = println("CKListener before")

  override def after(): Unit = println("CKListener after")
}

object FirstTest {
  def main(args: Array[String]): Unit = {

    val hooks: ListBuffer[TaskListener] = ListBuffer[TaskListener]()

    def register(hook: TaskListener): Unit = {
      hooks += hook
    }


    def safeInvoke(trigger: TaskListener => Unit): Unit = {
      hooks.foreach(it => {
        try {
          trigger(it)
        } catch {
          case ex: Exception => println(ex)
          case _ => ""
        }
      })
    }


    register(DorisListener())
    register(HiveListener())
    register(CKListener())
    safeInvoke(_.before())
  }
}
